package com.harzone.commons.search.statement;

import com.harzone.commons.search.domain.Condition;
import com.harzone.commons.search.domain.MethodCondition;
import com.harzone.commons.search.domain.Where;

/**
 * where条件
 * @author ls
 * 2014年11月21日下午3:16:08
 */
public abstract class BaseWhere {

	private Where where = null;
	
	private Where currentSubwhere = null;
	/**
	 * 添加查询条件
	 * @author ls
	 * 2014年11月22日下午3:23:43 
	 * @param condition
	 */
	public BaseWhere add(Condition condition){
		if(currentSubwhere!=null){
			currentSubwhere.addWhere(condition);;
		}else{
			if(this.where == null){
				where = Where.newInstance();
			}
			this.where.addWhere(condition);
		}
		return this;
	}

	
	public BaseWhere add(MethodCondition condition){
		if(currentSubwhere!=null){
			currentSubwhere.addWhere(condition);;
		}else{
			if(this.where == null){
				where = Where.newInstance();
			}
			this.where.addWhere(condition);
		}
		return this;
	}

	/**
	 * 开始定义where条件
	 * @author ls
	 * 2014年11月25日上午11:37:37 
	 * @param conn and / or
	 * @return
	 */
	public BaseWhere startWhere(String conn){
		if(this.where == null){
			where = Where.newInstance(conn);
		}
		return this;
	}
	

	/**
	 * 添加子查询
	 * @author ls
	 * 2014年11月22日下午3:24:00 
	 * @param subWhere
	 * @return
	 */
	public BaseWhere startSubWhere(Where subWhere){
		if(currentSubwhere!=null){
			currentSubwhere.addWhere(subWhere);
		}else{
			if(this.where == null){
				where = Where.newInstance();
			}
			this.where.addWhere(subWhere);
		}
		currentSubwhere = subWhere;
		return this;
	}
	
	/**
	 * 添加子查询
	 * @author ls
	 * 2014年11月24日下午2:32:14 
	 * @param conn
	 * @return
	 */
	public BaseWhere startSubWhere(String conn){
		Where subWhere = new Where(conn);
		if(currentSubwhere!=null){
			currentSubwhere.addWhere(subWhere);
		}else{
			if(this.where == null){
				where = Where.newInstance();
			}
			this.where.addWhere(subWhere);
		}
		currentSubwhere = subWhere;
		return this;
	}

	/**
	 * 子查询条件结束
	 * @author ls
	 * 2014年11月24日下午2:32:42 
	 * @return
	 */
	public BaseWhere endSubWhere(){
		currentSubwhere = null;
		return this;
	}
	public Where addWhere(Where subWhere){
		if(this.where == null){
			where = Where.newInstance();
		}
		this.where.addWhere(subWhere);
		return subWhere;
	}
	
	public boolean hasWhere(){
		return this.where!=null && this.where.hasWhere();
	}
	
	public Where getWhere() {
		return this.where;
	}

	public void setWhere(Where where) {
		this.where = where;
	}


	@Override
	public String toString() {
		return "BaseWhere [where=" + where + "]";
	}
}
